﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http.Filters;

namespace DaemonAPI.Filter.Reminder
{
	public abstract class BaseReminderAttribute : ActionFilterAttribute
	{
		public HttpMethod Method { get; private set; }

		public string RouteName { get; private set; }

		public string Url { get; private set; }

		protected string Token { get; private set; } = string.Empty;

		public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
		{
			base.OnActionExecuted(actionExecutedContext);

			if (actionExecutedContext.Request.Method == HttpMethod.Get || actionExecutedContext.Exception != null)
			{
				return;
			}

			var httpRequest = actionExecutedContext.Request;
			Method = httpRequest.Method;

			var path = httpRequest.RequestUri.LocalPath;
			RouteName = path.Split('/').LastOrDefault()?.ToLower() ?? string.Empty;

			Url = httpRequest.RequestUri.ToString();

			var token = httpRequest.Headers.GetValues("token").FirstOrDefault();
			if (!string.IsNullOrEmpty(token))
			{
				Token = token;
			}

			Remind(actionExecutedContext);
		}

		protected abstract void Remind(HttpActionExecutedContext actionExecutedContext);

		protected string GetQuerySingleValue(HttpActionExecutedContext actionExecutedContext, string name)
		{
			return actionExecutedContext.Request.GetQueryNameValuePairs().FirstOrDefault(i => string.Equals(i.Key, name, StringComparison.OrdinalIgnoreCase)).Value;
		}
	}
}
